package com.lsj.gulimall.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsj.common.constant.ProductConstant;
import com.lsj.common.utils.R;
import com.lsj.gulimall.product.dao.*;
import com.lsj.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.lsj.gulimall.product.entity.AttrEntity;
import com.lsj.gulimall.product.entity.CategoryEntity;
import com.lsj.gulimall.product.vo.AttrGroupRelationVo;
import com.lsj.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.lsj.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsj.common.utils.PageUtils;
import com.lsj.common.utils.Query;

import com.lsj.gulimall.product.entity.AttrGroupEntity;
import com.lsj.gulimall.product.service.AttrGroupService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {


    @Resource
    CategoryDao categoryDao;

    @Resource
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        IPage<AttrGroupEntity> page = null;
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_group_id",key).or().eq("sort",key).or().like("attr_group_name",key);
            });
        }
        if (catelogId ==0) {
            page = this.page(new Query<AttrGroupEntity>().getPage(params),
                    wrapper);
        } else {
           wrapper.eq("catelog_id",catelogId);
            page = this.page(new Query<AttrGroupEntity>().getPage(params),
                    wrapper);
        }
        return new PageUtils(page);
    }

    /**
     * 根据属性分组id获取属性分组详情
     * @param attrGroupId
     * @return
     */
    @Override
    public AttrGroupEntity getInfoById(Long attrGroupId) {
        AttrGroupEntity attrGroupEntity = baseMapper.selectById(attrGroupId);
        List<Long> categroyIds = new ArrayList<>();
        Long[] categroyPath = getCategroyIds(attrGroupEntity.getCatelogId(), categroyIds);
        attrGroupEntity.setCatelogPath(categroyPath);
        return attrGroupEntity;
    }

    /**
     * 递归获取完整的三级分类id数组
     * @param categroyId
     * @param categroyIds
     * @return
     */
    @Override
    public Long[] getCategroyIds(Long categroyId,List<Long> categroyIds) {
        CategoryEntity categoryEntity = categoryDao.selectById(categroyId);
        categroyIds.add(categoryEntity.getCatId());
        if (categoryEntity.getParentCid() !=0) {
            getCategroyIds(categoryEntity.getParentCid(),categroyIds);
        }
        Collections.reverse(categroyIds);
        return categroyIds.toArray(new Long[categroyIds.size()]);
    }

    /**
     * 根据分组id获取对应的分组属性
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrVo> getGroupAttrRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<AttrVo> attrVos = relations.stream().map(relation -> {
            AttrVo attrVo = new AttrVo();
            AttrEntity attrEntity = attrDao.selectById(relation.getAttrId());
            BeanUtils.copyProperties(attrEntity, attrVo);
            return attrVo;
        }).collect(Collectors.toList());
        return attrVos;
    }


    @Override
    public void deleteRelation(AttrGroupRelationVo[] ids) {
        if (ids.length > 0)  {
            for (int i = 0; i < ids.length; i++) {
                attrAttrgroupRelationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id",ids[i].getAttrId())
                        .eq("attr_group_id",ids[i].getAttrGroupId()));
            }
        }

    }

    /**
     * 获取属性分组没有关联的其他属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        AttrGroupEntity attrGroupEntity = this.baseMapper.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        // 获取已经关联分组的属性id
        List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>());
        List<Long> relationIds = null;
        if (relations != null && relations.size() > 0) {
            relationIds = relations.stream().map(relation -> {
                return relation.getAttrId();
            }).collect(Collectors.toList());
        }

        // 获取没有关联分组的属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id",catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (relationIds != null && relationIds.size() > 0) {
            wrapper.notIn("attr_id",relationIds);
        }
        String  key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.like("attr_name",key);
        }
        List<AttrEntity> attrEntities = attrDao.selectList(wrapper);
         IPage<AttrEntity> page = attrDao.selectPage(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    /**
     * 获取分类下所有分组&关联属性
     * @param catelogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrsVo> getGroupWithAttr(Long catelogId) {
        List<AttrGroupWithAttrsVo> vos = null;
        // 根据分类id获取分类下的所有分组
        List<AttrGroupEntity> attrGroups = this.baseMapper.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        if (attrGroups != null && attrGroups.size() > 0) {
            vos = attrGroups.stream().map(attrGroupEntity -> {
                AttrGroupWithAttrsVo vo = new AttrGroupWithAttrsVo();
                BeanUtils.copyProperties(attrGroupEntity,vo);
                // 获取分组关联的属性
                List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupEntity.getAttrGroupId()));
                List<AttrEntity> attrs = null;
                if (relations != null && relations.size() > 0) {
                    attrs = relations.stream().map(relation -> {
                        return attrDao.selectById(relation.getAttrId());
                    }).collect(Collectors.toList());
                    vo.setAttrs(attrs);
                }
                return vo;
            }).collect(Collectors.toList());
        }
        return vos;
    }

}